package user

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"weekly-exam-1/config"
	"weekly-exam-1/internal/model/dao"
	"weekly-exam-1/tools"
)

type Logins struct {
	Mobile   string `form:"mobile" json:"mobile" xml:"mobile"  binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func Login(c *gin.Context) {
	var json Logins
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var user dao.Users
	config.DB.Where("mobile=?", json.Mobile).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该用户未注册"})
		return
	}
	if user.Passwords != json.Password {
		c.JSON(http.StatusBadRequest, gin.H{"error": "密码错误,请重新输入"})
		return
	}
	jwtSign := tools.NewJWT(config.AppConfig.Jwt.Key)
	jwtclaims := tools.CustomClaims{
		ID:       user.ID,
		NickName: user.Mobile,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + config.AppConfig.Jwt.Expiry,
			Subject:   "userAccess",
		},
	}
	token, err := jwtSign.CreateToken(jwtclaims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "token生成失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "登录成功",
		"data": token,
	})
}
